import axios from "axios";
import { Notification } from "element-ui";
import store from "@/store";
import { uuid } from '@/utils/data';
import goLogin from '@/main.js'
const http = axios.create({
  timeout: 2000 * 500,
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
});

// const token = localStorage.getItem("token");
// const token = store.state.token

http.__proto__ = axios;
/**
 * 请求拦截 配置header请求参数
 */
http.interceptors.request.use(
  (config) => {
    config.headers.sn = new Date().getTime();
    config.headers["authToken"] = localStorage.getItem("token");
    config.headers.common.submitKey = uuid(16, 16)
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截
 */
http.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 请求地址处理djy-chuxin
 */
http.adornUrl = (actionName, type = "") => {
  return process.env.VUE_APP_BASE_URL + type + actionName;
};

/**
 * 封装ajax请求
 * 1.reqUrl、reqMethod为必填选项
 * 2.type存在时导出数据
 * @param {String}   reqUrl                   请求地址
 * @param {String}   reqMethod                请求方式
 * @param {JSON}     reqData                  请求数据
 * @param {Function} callback                 回调函数
 * @param {Function} dir                      直接返回响应数据
 */

const Ajax = (reqUrl, reqMethod, reqData, callback, dir, type) => {
  const isGet = reqMethod === "get" || reqMethod === "GET";
  store.commit("SET_LOADING");
  console.log(reqUrl)
  http({
    url: http.adornUrl(reqUrl, type),
    method: reqMethod,
    data: isGet ? {} : reqData,
    params: isGet ? reqData : {},
  })
    .then(({ data }) => {
      store.commit("SET_LOADING", false);
      if (dir) {
        callback(data);
      } else if (data && data.code === '0') {
        callback(data);
      } else if (data.code === '9') {
        goLogin()
      } else {
        Notification({
          title: "系统错误",
          message: data.code + "：" + data.message,
        });
      }
    })
    .catch((err) => {
      store.commit("SET_LOADING", false);
      Notification({
        title: "服务器错误",
        message: err,
      });
    });
};
export default {
  Ajax,
};
